package com.jz.digital.base;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.digital.R;
import com.jz.digital.utils.PermissionUtil;
import com.jz.digital.utils.ScreenUtil;
import com.jz.digital.utils.StatusBarsUtil;

import androidx.annotation.ColorInt;
import androidx.annotation.IntRange;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;


public abstract class BaseCoreActivity extends AppCompatActivity implements PermissionUtil.RequestResult {
    //权限请求工具类
    private PermissionUtil mPermissionUtil;
    //状态栏背景色是否是白色
    private boolean mStatusBgWhite = true;
    private Toast mToast;
    private long mLastClickTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        actionBeforeSetContentView();
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResId());
        getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
        getWindow().getDecorView().setTextDirection(View.TEXT_DIRECTION_LTR);
        if (ScreenUtil.getScreenW() == 0 || ScreenUtil.getScreenH() == 0) {
            ScreenUtil.initScreen(this);
        }
        initViews();
        initListening();
        initData();
        initEvent();
    }

    /**
     * 在设置View之前调用
     */
    protected void actionBeforeSetContentView() {
    }

    /**
     * View的初始化
     */
    protected void initViews() {

    }

    /**
     * 初始化监听
     */
    protected void initListening() {
    }

    /**
     * 初始化数据
     */
    protected void initData() {
    }

    /**
     * 事件相关
     */
    protected void initEvent() {
    }

    /**
     * 布局资源文件
     *
     * @return 布局资源文件
     */
    protected abstract @LayoutRes
    int getLayoutResId();

    /**
     * 检查权限
     *
     * @param permissions 权限
     * @return true 有权限，false无权限
     */
    public boolean checkSelfPermission(String... permissions) {
        return PermissionUtil.checkSelfPermission(this, permissions);
    }

    /**
     * 请求权限
     *
     * @param requestCode 请求code
     * @param permissions 权限
     */
    public void requestPermissions(int requestCode, String... permissions) {
        if (mPermissionUtil == null) mPermissionUtil = new PermissionUtil();
        mPermissionUtil.setRequestResult(this);
        PermissionUtil.requestPermissions(this, requestCode, permissions);
    }

    /**
     * 请求权限
     *
     * @param requestCode 请求code
     * @param permissions 权限
     */
    public void requestPermissions(int requestCode, PermissionUtil.RequestResult callback, String... permissions) {
        if (mPermissionUtil == null) mPermissionUtil = new PermissionUtil();
        mPermissionUtil.setRequestResult(callback);
        PermissionUtil.requestPermissions(this, requestCode, permissions);
    }

    /**
     * 请求权限
     *
     * @param requestCode 请求code
     * @param permissions 权限
     */
    public void requestPermissions(Activity activity,int requestCode, PermissionUtil.RequestResult callback, String... permissions) {
        if (mPermissionUtil == null) mPermissionUtil = new PermissionUtil();
        mPermissionUtil.setRequestResult(callback);
        PermissionUtil.requestPermissions(activity, requestCode, permissions);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mPermissionUtil != null)
            mPermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 权限请求成功
     *
     * @param requestCode 权限请求码
     */
    @Override
    public void requestPermissionsSuccess(int requestCode) {

    }

    /**
     * 权限请求失败
     *
     * @param requestCode 权限请求码
     */
    @Override
    public void requestPermissionsFail(int requestCode) {

    }

    public boolean isStatusBgWhite() {
        return mStatusBgWhite;
    }

    /**
     * 设置状态栏背景是否是白色
     */
    public void setStatusBgWhite(boolean statusBgWhite) {
        mStatusBgWhite = statusBgWhite;
        if (statusBgWhite) {
            setStatusBar(getColor(R.color.white), StatusBarsUtil.ALL_STATUS_BAR_ALPHA);
        } else {
            setStatusBar(getColor(R.color.translate), StatusBarsUtil.ALL_STATUS_BAR_ALPHA);
        }
    }
    /**
     * 设置全局的状态栏，默认是全透明
     *
     * @param color 状态栏背景色
     * @param alpha 状态栏透明度
     */
    protected void setStatusBar(@ColorInt int color, @IntRange(from = StatusBarsUtil.ALL_STATUS_BAR_ALPHA, to = StatusBarsUtil.NONE_STATUS_BAR_ALPHA) int alpha) {
        StatusBarsUtil.setColor(this, color, alpha);
        mStatusBgWhite = color == Color.WHITE;
        StatusBarsUtil.setStatusTextColor(this, mStatusBgWhite);
    }

    /**
     * 设置全局的状态栏，默认是全透明
     *
     * @param color 状态栏背景色
     * @param alpha 状态栏透明度
     */
    protected void setStatusBar(@ColorInt int color,
                                @IntRange(from = StatusBarsUtil.ALL_STATUS_BAR_ALPHA, to = StatusBarsUtil.NONE_STATUS_BAR_ALPHA) int alpha, boolean isWhite) {
        StatusBarsUtil.setColor(this, color, alpha);
        mStatusBgWhite = isWhite;
        StatusBarsUtil.setStatusTextColor(this, mStatusBgWhite);
    }

    /**
     * 设置状态栏颜色
     *
     * @param color 状态栏背景色  默认是全透明
     */
    protected void setStatusBarColor(@ColorInt int color) {
        setStatusBar(color, StatusBarsUtil.ALL_STATUS_BAR_ALPHA);
    }

    /**
     * 设置状态栏颜色
     *
     * @param color   状态栏背景色  默认是全透明
     * @param isWhite 状态栏是否是白色
     */
    protected void setStatusBarColor(@ColorInt int color, boolean isWhite) {
        setStatusBar(color, StatusBarsUtil.ALL_STATUS_BAR_ALPHA, isWhite);
    }

    /**
     * 弹出一个toast
     *
     * @param msg 字符串资源
     */
    public void showToast(String msg) {
        showToast(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 弹出一个toast
     *
     * @param msg 字符串资源
     */
    public void showToast(int msg) {
        showToast(getString(msg));
    }

    private Toast getToast(String text, int duration) {
        Toast toast = new Toast(this);
        LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.layout_normal_toast, null);
        TextView loading_msg = v.findViewById(R.id.txt_normal_tips);
        loading_msg.setText(text);
        toast.setView(v);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(duration);
        return toast;
    }

    /**
     * 正常显示 Toast
     *
     * @param text
     * @param duration
     */
    @SuppressLint("WrongConstant")
    public void showToast(String text, int duration) {
        if (TextUtils.isEmpty(text) || Thread.currentThread() != Looper.getMainLooper().getThread())
            return;
        boolean manualDismiss = false;
        /*if (duration != Toast.LENGTH_SHORT && duration != Toast.LENGTH_LONG) {
            if (duration < 1000) duration = 1000;
            manualDismiss = true;
        }*/
        if (duration == Toast.LENGTH_SHORT) {
            duration = 1000;
        } else if (duration == Toast.LENGTH_LONG) {
            duration = 2000;
        } else {
            if (duration < 1000) {
                duration = 1000;
            }
        }

        if (mToast == null) {
            mToast = getToast(text, duration);
        } else {
            mToast.cancel();
            TextView loading_msg = mToast.getView().findViewById(R.id.txt_normal_tips);
            if (loading_msg != null)
                loading_msg.setText(text);
        }
        /*if (manualDismiss) mToast.setDuration(Toast.LENGTH_LONG);
        else*/
        mToast.setDuration(duration);
        mToast.show();
        getWindow().getDecorView().postDelayed(() -> {
            if (mToast != null)
                mToast.cancel();
            mToast = null;
        }, duration);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isShouldHideInput(view, ev)) {
                InputMethodManager Object = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (Object != null) {
                    if (view != null) {
                        Object.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    //判断是否隐藏键盘
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v instanceof EditText) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    /**
     * 点击是否有效，防连续点击
     *
     * @return
     */
    protected boolean clickValid() {
        long currentTimeMillis = System.currentTimeMillis();
        if (Math.abs(mLastClickTime - currentTimeMillis) >= 500) {
            mLastClickTime = currentTimeMillis;
            return true;
        }
        return false;
    }
}